#ifndef _USERREGISTERSECTION1_HPP
#define _USERREGISTERSECTION1_HPP
#include "TcpConnection.hpp"
#include "TLV.hpp"
#include "Packet.hpp"
#include "MySQLClient.hpp"
#include "logger.hpp"
#include <string>
#include <cstdlib>
#include <ctime>
#include <cstdio>

using namespace wd;
using namespace std;

class UserRegisterSection1
{
private:
    TcpConnectionPtr _conn;
    Packet _packet;
    bool findname(const string& username);
    bool isEncryptValid(const string& username);
    char* GenRandomString(int length);
public:
    UserRegisterSection1(TcpConnectionPtr conn, Packet pack)
        : _conn(conn), _packet(pack) {}
    
    ~UserRegisterSection1() {}
    
    void process(){
        if(_packet.type == TASK_REGISTER_SECTION1) {
            // 处理注册请求
            string username = _packet._msg;
            MyLogger::getInstance().serverInfo("用户注册请求: " + username);
            if (findname(username)) {
                MyLogger::getInstance().serverInfo("用户名可用: " + username);
                // 生成随机盐值
                char* salt = GenRandomString(8);
                if(salt){
                    MyLogger::getInstance().serverInfo("生成随机盐值: " + string(salt));
                    // 继续处理注册逻辑
                    string saltStr(salt);
                    MyLogger::getInstance().serverInfo("将盐值放入数据库: " + saltStr);
                    //将用户名和盐值插入数据库
                    MySQLClient myclient;
                    if (!myclient.connect("localhost", 3306, "root", "1234", "shms")) {
                        MyLogger::getInstance().dbError("Database connection failed");
                        return;
                    }
                    string setting="$1$"+saltStr +"$";
                    string sql = "INSERT INTO shms_user (name, setting) VALUES ('" + username + "', '" + setting + "')";

                    TLV tlv;
                    if (myclient.writeOperationQuery(sql)) {
                        MyLogger::getInstance().serverInfo("用户注册成功: " + username);
                        tlv.setType(TASK_REGISTER_SECTION1_RESP_OK);
                        tlv.setLength(setting.size());
                        tlv.setData(setting);
                        
                    } else {
                        MyLogger::getInstance().serverInfo("用户注册失败: " + username);
                        tlv.setType(TASK_REGISTER_SECTION1_RESP_ERROR);
                        tlv.setLength(0);
                    }
                    _conn->sendInLoop(tlv);
                }else{
                    MyLogger::getInstance().serverInfo("生成随机盐值失败");
                }
            }else{
                //若查找用户名查找到了且数据库的密文不为空，则注册失败，防止出现注册一半的情况
                MyLogger::getInstance().serverInfo("用户名已存在: " + username);
                if(isEncryptValid(username)){
                    MyLogger::getInstance().serverInfo("用户名已存在且密文有效: " + username);
                    // 发送注册失败响应
                    TLV tlv;
                    tlv.length=0;
                    tlv.type=TASK_REGISTER_SECTION1_RESP_ERROR;
                    _conn->sendInLoop(tlv);
                }else{
                    MyLogger::getInstance().serverInfo("密文不存在，该用户名可用");
                    MySQLClient mysqlclient;
                    mysqlclient.connect("localhost", 3306, "root", "1234", "shms");
                    string setting = mysqlclient.getSetting(username);
                    TLV tlv;
                    tlv.setType(TASK_REGISTER_SECTION1_RESP_ERROR);
                    tlv.setLength(setting.size());
                    tlv.setData(setting);
                    _conn->sendInLoop(tlv);
                }
            }
        }
    }
};

inline bool UserRegisterSection1::findname(const string &username)
{
    // 1. 创建数据库连接
    MySQLClient myclient;
    bool ret = myclient.connect("localhost", 3306, "root", "1234", "shms");
    if (!ret) {
        MyLogger::getInstance().dbError("Database connection failed in isUsernameAvailable");
        return false; // 连接失败，为安全起见返回false（不允许注册）
    }
    
    // 2. 查询用户名是否存在
    string sql = "SELECT name FROM shms_user WHERE name = '" + username + "'";
    vector<vector<string>> result = myclient.readOperationQuery(sql);
    
    // 3. 返回结果
    // 如果查询结果为空，说明用户名不存在，可用
    // 如果查询结果非空，说明用户名已存在，不可用
    return result.empty();
}

inline bool UserRegisterSection1::isEncryptValid(const string &username)
{   
    MySQLClient myclient;
    if (!myclient.connect("localhost", 3306, "root", "1234", "shms")) {
        MyLogger::getInstance().dbError("Database connection failed in isPasswordValid");
        //数据库连接失败，返回true，不让它继续注册
        return true;
    }
    // 进行数据库查询，检查用户名的加密信息是否存在
    string sql = "SELECT encrypt FROM shms_user WHERE name = '" + username + "'";
    vector<vector<string>> result = myclient.readOperationQuery(sql);
    
    // 检查查询结果
    // 1. 如果查询结果为空，说明用户不存在，返回false
    if (result.empty()) {
        return false;
    }
    
    // 2. 如果查询到了结果，检查encrypt字段是否为空或NULL
    // result[0][0] 是第一行第一列的数据，即encrypt字段的值
    if (result[1].empty() || result[1][0].empty()) {
        // encrypt字段为空或NULL，密文不存在
        MyLogger::getInstance().serverInfo("encrypt字段为NULL，密文不存在");
        return false;
    }
    
    // 3. encrypt字段有值，密文存在
    MyLogger::getInstance().serverInfo("encrypt字段有值: " + result[1][0]);
    return true;
}
inline char* UserRegisterSection1::GenRandomString(int length)
{
    int flag, i;  
    char* string;  
    srand((unsigned) time(NULL ));  
    if ((string = (char*) malloc(length)) == NULL )  {  
        printf("malloc failed!flag:14\n");  
        return NULL ;  
    }  
    for (i = 0; i < length+1; i++)  {  
        flag = rand() % 3;  
        switch (flag)  {  
            case 0:  string[i] = 'A' + rand() % 26;  break;  
            case 1:  string[i] = 'a' + rand() % 26;  break;  
            case 2:  string[i] = '0' + rand() % 10;  break;  
            default:  string[i] = 'x';  break;  
        }
    }
    string[length] = '\0';
    return string;
}

#endif
